import { defineStore } from 'pinia'
import { postWithAns } from '@renderer/api/http'
import API from '@renderer/api/constant'
import { alertMessageType, diskInfoType } from '@renderer/types'
import { router } from '@renderer/routers'
import routeConstants from '@renderer/routers/routeConstants'
import { useSystemSettingStore } from '@renderer/store/pinia/systemSetting'
import { MediaConnection } from 'peerjs'
import { ServerPeer } from '@renderer/utils/PeerHelper/ServerPeer'

const useSystemStore = defineStore('system', {
  state: () => {
    return {
      userID: '',
      username: '',
      authList: [],
      scanBtnStatus: 'inactive', // 'move' 'scan', 'scanClicked'
      connectStates: {
        dicom: false,
        system: false,
        breath: false,
        gateway: false
      },
      remoteDeskClients: [] as any[],
      remoteDeskServer: null as any,
      remoteDeskConnectStatus: {
        connect2Server: false,
        connect2Peer: false,
        callMap: new Map<number, MediaConnection>()
      },
      lasePosition: {
        current: 0
      },
      laserOpen: false,
      diskInfo: [] as diskInfoType[],
      systemAlertCount: 0,
      alertMessageList: [] as alertMessageType[],
      bulbHeating: false
    }
  },
  getters: {
    disconnectCount: (state) => {
      return Array.from(Object.values(state.connectStates)).filter(val => val === false).length
    },
    diskWarningCount: (state) => {
      if (state.diskInfo.length === 0) {
        return 0
      }
      return state.diskInfo.filter(eachDisk => {
        const used = eachDisk.usedInfo?.used || 0
        const total = eachDisk.usedInfo?.total || 100
        const limit = eachDisk.upperLimit || 50
        const usedPercent = used / total * 100
        return usedPercent >= Number(limit)
      }).length
    }
  },
  actions: {
    handleToggleLaser() {
      console.log('发出激光灯请求');
      postWithAns(API.setLaser, null, {
        laserFlag: !this.laserOpen
      })
    },
    setDiskInfoPanel(payload: any) {
      if (this.diskInfo.length > 0) {
        Object.assign(this.diskInfo[0], payload)
      } else {
        this.diskInfo = [payload]
      }
    },
    setDiskInfo(payload) {
      if (this.diskInfo.length > 0) {
        const newObj = Object.assign({}, this.diskInfo[0], payload[0])
        this.diskInfo = [newObj, ...payload.slice(1)]
      } else {
        this.diskInfo = payload
      }
    },
    async getAlertMessageList() {
      this.alertMessageList = (await postWithAns(API.getSystemWarning)) as alertMessageType[]
    },
    async logout() {
      this.userID = ''
      this.username = ''
      this.authList = []
      const systemSettingStore = useSystemSettingStore()
      systemSettingStore.access_token = ''
      await router.push(routeConstants.LoginPage.path)
    },
    async getAccountInfoByToken() {
      const systemSettingStore = useSystemSettingStore()
      if (systemSettingStore.access_token === '') {
        await this.logout()
      } else {
        const res: any = await postWithAns(API.getProfile)
        this.userID = res.user.userId
        this.username = res.user.username
      }
    },
    startRemoteConnect() {
      this.remoteDeskServer = new ServerPeer((state) => {
        Object.assign(this.remoteDeskConnectStatus, state)
        this.remoteDeskClients = Array.from(this.remoteDeskConnectStatus.callMap.keys())
      })
    },
    disconnect2OneClient(key: number) {
      this.remoteDeskServer.disconnect2PeerCall(key)
    }
  }
}) as any


export {
  useSystemStore
}

